from django import http
from django.conf import settings
from django.urls import reverse


from django.contrib.auth import login
from django.shortcuts import render, redirect

# Create your views here.

from django.views import View

from apps.oauth.models import OAuthQQUser

from meiduo_mall.settings.dev import logger
from utils.response_code import RETCODE


def is_bind_openid(openid,request):
    try:
        oauth_user=OAuthQQUser.objects.get(openid=openid)
    except Exception as e:
        logger.error(e)
        #未绑定了---跳转到绑定的页面
        context={"openid":openid}
        return render(request,"oauth_callback.html",context)
    else:
        #1.绑定--保持登陆状态--设置username--cookie--跳转到首页
        user=oauth_user.user
        #保持登陆状态
        login(request,user)
        #设置username-cookie
        response=redirect(reverse("contents:index"))
        #跳转到首页
        response.set_cookie("username",user.username,max_age=3600*24*14)
        return response
    #QQ登陆--code--token--openid

class QQAuthUserView(View):
    def get(self,request):
        code=request.GET.get("code")
        if not code:
            return http.HttpResponseForbidden("缺少code")
        from QQLoginTool.QQtool import OAuthQQ
        oauth=OAuthQQ(client_id=settings.QQ_CLIENT_ID,client_secret=settings.QQ_CLIENT_SECRET,redirect_uri=settings.QQ_REDIRECT_URI)
        try:
            #code--token
            access_token=oauth.get_access_token(code)
            #token--openid
            openid=oauth.get_open_id(access_token)
        except Exception as e:
            logger.error(e)
            return http.HttpResponseServerError("Oauth2.0认证失败")
        #判断是否绑定了openid
        response=is_bind_openid(openid,request)
        #返回前端
        return response
class QQAuthURLView(View):
    def get(self,request):
        #实例化qq认证类
        from QQLoginTool.QQtool import OAuthQQ
        oauth_qq =OAuthQQ(
            client_secret=settings.QQ_CLIENT_SECRET,
            client_id=settings.QQ_CLIENT_ID,
            redirect_uri=settings.QQ_REDIRECT_URI
        )
        #2.获取登陆网址
        login_url=oauth_qq.get_qq_url()
        #返回给前端
        return http.JsonResponse({"code":RETCODE.OK,"errmsg":"OK","login_url":login_url})



